package com.atnjupt.web;


import com.atnjupt.bean.User;
import com.atnjupt.service.UserService;
import com.atnjupt.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Wizarder
 * @create 2021-05-27 21:13
 */
public class RegistServlet extends HttpServlet {
    private UserServiceImpl usi = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        //验证验证码-这里验证码写死==abcd
        if("abcd".equalsIgnoreCase(code)){
                //验证码正确
            //验证用户名是否存在
            boolean isExist = usi.existUsername(username);
//            System.out.println(isExist);
            if(isExist){
                //用户名已存在信息传回客户端
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("password",password);
                req.setAttribute("email",email);
                req.setAttribute("code",code);
                System.out.println("用户名存在");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else{
                //保存到数据库中，用户注册成功
                usi.registUser(new User(1,username,password,email));
                //跳转注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }

        }else{
            //验证码不同停留此界面
            //验证码输入错误信息回传客户端
            req.setAttribute("msg","验证码输入有误！");
            //保存用户输入的信息
            req.setAttribute("username",username);
            req.setAttribute("password",password);
            req.setAttribute("email",email);
            System.out.println("验证码[" + code +"]不正确");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }


    }
}
